package com.sdhillon.gallery;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.sdhillon.util.Util;

public class FlickrHelper {
	private static final String API_KEY = "YOUR API KEY";
	private static final String HOSTNAME = "http://api.flickr.com/services/rest/";

	public static final class FlickrResult {
		int totalPages = 1;
		ArrayList<String> thumbnailUrls = new ArrayList<String>();
		ArrayList<String> mediumUrls = new ArrayList<String>();
		ArrayList<String> titles = new ArrayList<String>();
	}

	/**
	 * Query the Flickr web service for a group's images page at a time.
	 * 
	 * @param groupId
	 *            The groupId for a Flickr Group
	 * @param page
	 *            the specific page requested
	 * @return a Result object containing the total pages, thumbnail urls,
	 *         medium urls, and titles
	 * @throws IOException
	 */
	public static final FlickrResult getGroupPhotos(String groupId, int page)
			throws IOException {
		String path = HOSTNAME
				+ "?method=flickr.photos.search&extras=url_m,url_t&per_page=18&format=json&nojsoncallback=1&api_key="
				+ API_KEY + "&group_id=" + groupId + "&page=" + page;

		FlickrResult result = new FlickrResult();
		try {
			String jsonString = Util.convertStreamToString(new URL(path)
					.openStream());
			JSONObject json = new JSONObject(jsonString);
			JSONObject photosObj = json.getJSONObject("photos");
			JSONArray photos = photosObj.getJSONArray("photo");
			// store result
			for (int i = 0; i < photos.length(); i++) {
				JSONObject jPhoto = photos.getJSONObject(i);
				result.thumbnailUrls.add(jPhoto.getString("url_t"));
				result.mediumUrls.add(jPhoto.getString("url_m"));
				result.titles.add(jPhoto.getString("title"));
			}
			result.totalPages = photosObj.getInt("pages");
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return result;
	}
}
